<style lang='less' scoped>
	@import './imgs-manager.css';
</style>
<template>
	<Card class="card" style="width: 100%;height: 100%">
		<div class="img-manager-btn-container">
      <div>
        <Tag size="medium"  v-for="(item,index) in fileTypes" :checked="item.checked" @on-change="filterChange(index)"  checkable color="primary">{{item.name}}</Tag>
      </div>
      <div class="btn-op-wrap">
        <Dropdown @on-click="toMove" trigger="click">
          <Button type="primary" :disabled="checkList.length==0" class="btn" style="height: 32px;">
            移动
            <Icon type="ios-arrow-down"></Icon>
          </Button>
          <DropdownMenu slot="list">
            <DropdownItem :name="item.id" v-for="item in folders">{{item.name}}</DropdownItem>
          </DropdownMenu>
        </Dropdown>
        <Button style="height: 32px;" type="error" :disabled="checkList.length==0" class="btn" @click="delImgs">删除
        </Button>
        <Upload
          action="api/admin/Imgs/uploadImg"
          multiple
          :on-success="handleSuccess"
          :show-upload-list="false"
          :headers="headers"
          :format="fileFormat"
          :on-format-error="handleFormatError"
          :max-size="maxSize"
          :on-exceeded-size="handleMaxSize"
          :data="params">
          <Button type="success" class="btn" icon="ios-cloud-upload-outline">上传</Button>
        </Upload>
      </div>

		</div>
		<Row class="content">
			<Col class="left-wrap" span="4">
				<div class="add-folder" @click="addFolder()">
					<Icon type="md-add-circle" size="24"/>
				</div>
				<div class="catalog-item" :class="selectedFolderIndex==-1?'catalog-checked':''" @click="folderSelected(-1)">
					<div>
						<Icon type="md-folder" size="24"/>
						<span>全部</span>
					</div>
				
				</div>
				<div v-for="item,index in folders" class="catalog-item" :class="selectedFolderIndex==index?'catalog-checked':''"
				     @click="folderSelected(index)">
					<div>
						<Icon type="md-folder" size="24"/>
						<span>{{item.name}}</span>
					</div>
					
					<Dropdown @on-click="menuSelected" class="hide showOp">
						<a href="javascript:void(0)">
							<Icon color="#888e9c" type="md-construct" size="16"/>
						</a>
						<DropdownMenu slot="list">
							<DropdownItem :name="index+'-1'">重命名</DropdownItem>
							<DropdownItem :name="index+'-2'">删除</DropdownItem>
						</DropdownMenu>
					</Dropdown>
				
				</div>
			</Col>
			<Col class="right-wrap" span="20">
				<div class="imgs-container">
					<div class="imgs-wrap">
						<template v-if="imgList!=null&&imgList.length>0" v-for="item,index in imgList">
							<div class="img-item" :key="item.url" :class="item.selected?'item-selected':''" @click="selected(index)"
							     :style="{'background-image':'url('+getShowUrl(item)+')'}">
								<div v-if="item.selected" class="mask"></div>
								<span class="item-name">{{item.file_name}}</span>
								<span class="item-top"> </span>
								<Icon type="ios-eye-outline" class="item-view" size="30" color="white"
								      @click.stop="handleView(item)"></Icon>
								<Icon class="item-check" v-if="item.selected" size="30" color="white" type="md-checkmark"/>
								<Icon class="item-del" @click.stop="delImg(item.id)" color="white" size="28" type="md-trash"/>
							</div>
						</template>
					</div>
					<Page :total="total" :page-size="20" :simple="true" @on-change="pageChange" :current="page"/>
				</div>
			</Col>
		</Row>
		<Modal title="预览" v-model="visible">
			<div v-if="visible">{{tempItme.trueUlr}}</div>
			<template v-if="visible">
				<video v-if="tempItme.file_type===typeVideo" :src="tempItme.trueUlr" style="width: 100%" controls="controls"></video>
				<img v-else :src="tempItme.showUrl"  style="width: 100%">
			</template>
			
		</Modal>
	</Card>

</template>
<script>
  import {getToken,VIDEO,getPre,FILEFORMATS} from '@/libs/util'
  import {getFolders, getImgs, delImg, addFolder, delFolder, renameFolder, move, delImgs} from '@/api/imgs'
  
  export default {
    name: 'ImgsManager',
    data() {
      return {
        fileTypes:[{id:0,checked:false,name:'图片'},{id:1,checked:false,name:'视频'},{id:10,checked:false,name:'其它'}],
        typeVideo:VIDEO,
        tempItme: null,
        visible: false,
        params: null,
        headers: null,
        selectedFolderIndex: -1,
        page: 1,
        folders: [],
        imgList: [],
        total: 0,
        folderName: '',
        checkList: [],
        checkImgs: [],
        fileFormats: FILEFORMATS,
        fileFormat: [],
        fileFormatName: null
      }
    },
    props: {
      maxSize: {
        type: Number, default: 50 * 1024
      },
      format: {type: String, default: null},
      countLimit: {type: Number, default: -1},
    },
    watch: {
      format: {
        immediate: true,
        handler(fileList) {
          let vm = this;
          if (vm.format !== null) {
            if (vm.format === 'img') {
              vm.fileFormat = vm.fileFormats.img;
              vm.fileFormatName = '图片';
            } else if (vm.format === 'video') {
              vm.fileFormat = vm.fileFormats.video;
              vm.fileFormatName = '视频';
            }
          }
        }
      }
    },
    created() {
//      this.init();
    },
    methods: {
      filterChange(index){
        this.fileTypes[index].checked = !this.fileTypes[index].checked;
        this.page = 1;
        this.total = 0;
        this.getImgs();
      },
      handleView(item) {
        this.tempItme = item;
        this.tempItme.showUrl = getPre(this,item, false);
        this.visible = true;
      },
	    getShowUrl(item){
        return getPre(this,item, false);
	    },
      selected(index) {
        //检查数量
        if (this.countLimit > 0 && !this.imgList[index].selected) {
          if (this.checkImgs.length === this.countLimit) {
            this.$Message.warning('最多只能选' + this.countLimit + '个');
            return;
          }
        }
        //检查格式
        let item = this.imgList[index];
        if (this.fileFormat != null && this.fileFormat.length) {
          const _file_format = item.url.split('.').pop().toLocaleLowerCase();
          const checked = this.fileFormat.some(v => v.toLocaleLowerCase() === _file_format);
          if (!checked) {
            this.$Message.warning('文件类型错误，请选择' + this.fileFormatName);
            return false;
          }
        }

        this.imgList[index].selected = !this.imgList[index].selected;
        if (item.selected) {
          this.checkList.push(item.id);
          this.checkImgs.push(item.name)
        } else {
          //将选中的移除
          for (let i = 0; i <= this.checkList.length; i++) {
            if (this.checkList[i] === item.id) {
              this.checkList.splice(i, 1);
              this.checkImgs.splice(i, 1);
              break;
            }
          }
        }
        this.$emit('on-checked-imgs', this.checkImgs);
      },
      folderSelected(index) {
        if (this.selectedFolderIndex === index) {
          return;
        }
        this.page = 1;
        this.selectedFolderIndex = index;
        this.getImgs();
        if (index === -1) {
          this.params = null;
        } else {
          this.params = {'fid': this.folders[index].id};
        }
      },
      handleSuccess(res, file) {
        let item = {
          url: res.data.url,
          name: res.data.name,
          selected: false,
          file_name: res.data.file_name,
          id: res.data.id,
          file_type: res.data.file_type
        };
        this.imgList.unshift(item);
        this.total++;
      },

      init() {
        let vm = this;
        vm.headers = {'apiAuth': getToken()};
        vm.getFolders();
        vm.getImgs();
      },
      getFolders() {
        let vm = this;
        getFolders().then(response => {
          let res = response.data;
          vm.folders = res.data;
        });
      },
      reSet() {
        this.checkList = [];
        this.checkImgs = [];
        this.imgList.forEach(v => {
          v.selected = false;
        });
        this.init();
      },
      getImgs() {
        let vm = this;
        vm.checkList = [];
        vm.checkImgs = [];
        let params = {page:vm.page,fid:vm.selectedFolderIndex === -1 ? null : vm.folders[vm.selectedFolderIndex].id};
        let fileTypes = [];
        vm.fileTypes.forEach(v=>{
          if(v.checked){
            fileTypes.push(v.id);
          }
        });
        if(fileTypes.length>0){
          params.fileType = JSON.stringify(fileTypes);
        }
        getImgs(params).then(response => {
          let res = response.data;
          let list = res.data.list;
          vm.total = res.data.count;
          let fortmatList = [];
          for (let i in list) {
            list[i].selected = false;
            // vm.setFileType(list[i]);
            fortmatList.push(list[i]);
          }
          vm.imgList = fortmatList;
        })
      },
      delImg(id) {
        let vm = this;
        delImg(id).then(response => {
          vm.$Message.success(response.data.msg)
          vm.getImgs();
        })
      },
      handleFormatError(file) {

        this.$Notice.warning({
          title: '格式错误',
          desc: file.name + ' 格式错误.'
        });
      },
      handleMaxSize(file) {
        this.$Notice.warning({
          title: '超过文件大小限制',
          desc: '文件最大不超过 ' + maxSize + 'KB.'
        });
      },
      addFolder() {
        let vm = this;
        vm.$Modal.confirm({
          title: '添加分类',
          render: (h) => {
            return h('Input', {
              props: {
                autofocus: true,
                maxlength: 30,
                placeholder: '请输入分类名字'
              },
              on: {
                input: (val) => {
                  vm.folderName = val;
                }
              }
            })
          },
          onOk: () => {
            if (vm.folderName.length === 0) {
              vm.$Message.warning('请输入分类名称');
              return false;
            } else {
              vm.doAddFolder();
            }
          }
        })
      },
      doAddFolder() {
        let vm = this;
        addFolder(this.folderName).then(response => {
          vm.$Message.success('添加成功');
          vm.folders.push(response.data.data);
        })
      },
      renameFolder(index) {
        let vm = this;
        vm.$Modal.confirm({
          title: '重命名分类',
          render: (h) => {
            return h('Input', {
              props: {
                autofocus: true,
                maxlength: 30,
                placeholder: '请输入分类名字'
              },
              on: {
                input: (val) => {
                  vm.folderName = val;
                }
              }
            })
          },
          onOk: () => {
            if (vm.folderName.length === 0) {
              vm.$Message.warning('请输入分类名称');
              return false;
            } else {
              vm.doRenameFolder(index, vm.folderName);
            }
          }
        })
      },
      doRenameFolder(index, name) {
        let vm = this;
        renameFolder(vm.folders[index].id, name).then(response => {
          vm.folders[index].name = name;
          vm.$Message.success(response.data.msg);
        })
      },
      delFolder(index) {
        let vm = this;
        this.$Modal.confirm({
          title: '确认删除吗',
          content: '<p>删除分类后分类下的图片不会被删除</p>',
          onOk: () => {
            vm.doDelFolder(index);
          },
          onCancel: () => {
          }
        });
      },
      doDelFolder(index) {
        let vm = this;
        delFolder(vm.folders[index].id).then(response => {
          vm.folders.splice(index, 1);
          vm.folderSelected(-1);
          vm.$Message.success(response.data.msg);
        })
      },
      menuSelected(name) {
        let strs = name.split('-');
        if (strs[1] === '1') {
          //重命名
          this.renameFolder(strs[0]);
        } else if (strs[1] === '2') {
          //删除
          this.delFolder(strs[0])
        }
      },
      toMove(id) {
        let vm = this;
        move(vm.checkList, id).then(response => {
          vm.checkList = [];
          vm.getImgs();
          vm.$Message.success(response.data.msg);
        })
      },
      delImgs() {
        let vm = this;
        delImgs(vm.checkList).then(response => {
          vm.checkList = [];
          vm.getImgs();
          vm.$Message.success(response.data.msg);
        })
      },
      pageChange(page) {
        let vm = this;
        vm.page = page;
        vm.getImgs();
      }
    }
  }
</script>
